﻿using System.IO;
using NAudio.Wave;
using System;

namespace PT.NoteDetection.Wave {
    public class WaveStreamAudioCapture : AudioCapture {

        readonly WaveFileReader reader;
        const int ReadBufferSize = 1024;

        public WaveStreamAudioCapture(Stream waveFile) {
            reader = new WaveFileReader(waveFile);

            var expectedWaveFormat = WaveFormat.CreateIeeeFloatWaveFormat(reader.WaveFormat.SampleRate, 1);

            if (!reader.WaveFormat.Equals(expectedWaveFormat)) {
                throw new ArgumentException("Input WAV stream must be a mono (single channel) 32-bit IEEE float encoded stream.");
            }
        }

        public override void Start() {
            IsCapturing = true;

            var buffer = new byte[ReadBufferSize];
            int read;

            while ((read = reader.Read(buffer, 0, ReadBufferSize)) > 0) {
                Output.Write(buffer, 0, read);
                OnNewData();
            }

            IsCapturing = false;
        }

        public override void Stop() {
            if (!IsCapturing) {
                return;
            }

            IsCapturing = false;
        }
    }
}
